package com.story.service;

import com.story.spring.BeanPostProcessor;
import com.story.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class StoryBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if(beanName.equals("userService")){
            System.out.println("userService 调用了BeanPostProcessor的postProcessBeforeInitialization方法");
        }else{
            System.out.println("调用了BeanPostProcessor的postProcessBeforeInitialization方法");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if(beanName.equals("userService")){
            Object proxyInstance = Proxy.newProxyInstance(StoryBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("切面逻辑");
                    return method.invoke(bean, args);
                }
            });
//            System.out.println("userService 调用了BeanPostProcessor的postProcessAfterInitialization方法");
            return proxyInstance;
        }
        return bean;
    }
}
